package com.myzk.example.core.serializer;

import com.myzk.example.base.Serializer;
import com.myzk.example.core.Result;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author mayong
 * @date 2020年04月07日
 */
public class JdkSerializer<T> implements Serializer<T> {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	public  byte[] serialize(T t) {
		try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
				ObjectOutputStream os = new ObjectOutputStream(bos);) {
			os.writeObject(t);
			return bos.toByteArray();
		} catch (IOException e) {
			logger.error("Jdk serializer error:{}",e.getMessage());
		}
		return new byte[0];
	}

	@Override
	public <T> T deserialize(byte[] bytes) {
		try(ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
		ObjectInputStream is = new ObjectInputStream(bis);){
			Object object = is.readObject();
			return (T) object;
		}catch (Exception e) {
			logger.error("Jdk deserialize error:{}",e.getMessage());
		}
		return null;
	}

	public static void main(String[] args) {
		Result<Map> result = new Result<>();
		result.setCode("200");
		result.setMessage("交易成功");
		result.setSuccess(true);
		result.setData(new HashMap());
		JdkSerializer<Result> serializer = new JdkSerializer<>();
		byte[] serialize = serializer.serialize(result);
		String encode = Base64.encodeBase64String(serialize);
		System.out.println("encode=" + encode);
		Result<Map> obj = serializer.deserialize(serialize);
		System.out.println(obj);
	}
}